import { asyncRoutes } from '@/router'

// /**
//  * grantedPolicies object to Permissions array
//  * @param grantedPolicies
//  */
// function convertToPermissions(grantedPolicies) {
//   const authPermissions = []
//   if (grantedPolicies) {
//     Object.keys(grantedPolicies).forEach(key => {
//       if (grantedPolicies[key]) {
//         authPermissions.push(key)
//       }
//     })
//   }
//   return authPermissions
// }

/**
 * Use meta.role to determine if the current user has permission
 * @param permissions
 * @param route
 */
function hasPermission(permissions, route) {
  if (route.meta && route.meta.roles && route.meta.roles.length > 0) {
    return permissions.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param permissions
 */
export function filterAsyncRoutes(routes, permissions) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }

    if (hasPermission(permissions, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, permissions)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  authorizedPermissions: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    // state.routes = constantRoutes.concat(routes)
    state.routes = routes
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.authorizedPermissions = permissions
  }
}

const actions = {
  generateRoutes({ commit }, { permissions }) {
    return new Promise(resolve => {
      // if (permissions.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      commit('SET_PERMISSIONS', permissions)
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
